<template>
  <div>
    <Button type="primary" class="back-button" @click="$router.push({path:`/game-score-management/${$config.kindNameUrl(fieldObj.kindCode)}${fieldObj.eventsId}`})" icon="md-arrow-back">返回上一级</Button>
    <Card>
      <Row class="m-b-sm" style="font-weight:bold;">
        <span>赛事名称：</span><span v-text="$config.userName(fieldObj.eventsName,fieldObj.eventsEnglishName)"></span>
      </Row>
      <Table stripe border :columns="fieldColumns" :data="fieldData"></Table>
    </Card>
    <Row v-if="stateFlag" class="m-t-sm m-b-sm right">
      <upload-excel-button @upload="getFieldData" text="重新上传"></upload-excel-button>
      <Button class="m-l-sm" @click="downloadTemp">下载模板</Button>
      <!-- <Button @click="del" class="m-l-sm">删除成绩</Button>
      <Button @click="save" class="m-l-sm" type="primary">保存</Button> -->
    </Row>
    <Card v-if="stateFlag">
      <Row>
        <Tabs type="card" v-if="fieldObj.kindCode=='-1' || fieldObj.kindCode=='0'"  @on-click="currentTab">
          <TabPane v-for="(items, index) in tabsList" :key="index" :label="tabsObj[items]" :name="items">
            <Table stripe border :loading="loading" :columns="tableColumns" :data="tableData[items]"></Table>
          </TabPane>
        </Tabs>
        <Table v-else stripe border :loading="loading" :columns="tableColumns" :data="tableData"></Table>
      </Row>
    </Card>
    <Card v-if="stateFlag==false" class="center m-t-sm">
      <Row>
        <upload-excel @upload="getFieldData"></upload-excel>
      </Row>
      <Row style="color:#D4D4D4;font-size:12px;" class="m-t-sm"><span>请选择本地EXCEL文件以录入单场比赛成绩</span></Row>
      <Row class="m-t-sm" style="font-size:12px;"><a @click="downloadTemp">下载比赛成绩模板（EXCEL）</a></Row>
    </Card>
    <spin-temp v-if="isUpload"></spin-temp>
  </div>
</template>

<script>
import dictSpan from "_c/dict/dict-span.vue";
import uploadExcel from "_c/upload/upload-excel.vue";
import uploadExcelButton from "_c/upload/upload-excel-button.vue";
import Api from "@/api/game-score";
import { getDict } from "@/api/configure";
const api = new Api();
// 赛事单场比赛成绩新增
export default {
  components: {
    dictSpan,
    uploadExcel,
    uploadExcelButton
  },
  data() {
    return {
      loading: true,
      fieldId: this.$route.params.id,
      AGOUTS: [],
      AGINS: [],
      page: {
        fieldId: this.$route.params.id
        // pageSize: this.$config.PAGE_SIZE,
        // pageNo: 1
      },
      total: 0,
      stateFlag: null, // 成绩是否录入
      isUpload: false,
      uploadData: [],
      // 比赛阶段
      fieldColumns: [
        // {
        //   title: "赛事类型",
        //   key: "kindCode",
        //   align: "left",
        //   render: (h, params) => {
        //     return h(dictSpan, {
        //       props: {
        //         code: "ZGX_SSDJ",
        //         value: params.row.kindCode
        //       }
        //     });
        //   }
        // },
        // {
        //   title: "比赛级别",
        //   key: "gradeCode",
        //   align: "left",
        //   width: 100,
        //   render: (h, params) => {
        //     return h(dictSpan, {
        //       props: {
        //         code: "ZGX_BSJB",
        //         parentCode: params.row.kindCode,
        //         value: params.row.gradeCode
        //       }
        //     });
        //   }
        // },
        {
          title: "比赛阶段",
          type: "fieldNumber",
          width: 100,
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              this.$config.fieldNumberStr(params.row.fieldNumber)
            );
          }
        },
        {
          title: "单场比赛名称",
          key: "fieldName",
          align: "left",
          render: (h, params) => {
            let self = this;
            let title = self.$config.userName(
              params.row.fieldName,
              params.row.fieldEnglishName
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "标准杆数",
          key: "roundStandard",
          align: "left"
        },
        {
          title: "比赛时间",
          key: "fieldTime",
          align: "left",
          // ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.getDate(
              params.row.fieldTime,
              params.row.fieldEndTime
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "比赛地点",
          key: "fieldAddressProvince",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = self.$config.fieldAddress(
              params.row,
              self.AGOUTS,
              self.AGINS
            );
            return h("span", { domProps: { title } }, title);
          }
        },
        {
          title: "比赛球场名称",
          key: "fieldCourt",
          align: "left",
          ellipsis: true,
          render: (h, params) => {
            let self = this;
            let title = params.row.fieldCourt;
            return h("span", { domProps: { title } }, title);
          }
        },

        {
          title: "成绩状态",
          key: "scoreState",
          align: "left",
          width: 90,
          render: (h, params) => {
            return h(dictSpan, {
              props: {
                code: "ZGX_CJZT",
                value: params.row.scoreState
              }
            });
          }
        },
        {
          title: "录入时间",
          key: "writeTime",
          align: "left",
          width: 110,
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.getDate(params.row.writeTime));
          }
        },
        {
          title: "阵容值",
          key: "kindTeamAll",
          align: "left",
          width: 90,
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.kindTeamAll));
          }
        },
        {
          title: "阵容加分",
          key: "kindTeamScore",
          align: "left",
          width: 90,
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.kindTeamScore));
          }
        },
        {
          title: "总计",
          key: "total",
          align: "left",
          width: 90,
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.total));
          }
        }
      ],
      fieldObj: {},
      fieldData: [],
      // 选手名次
      tableColumns: [
        {
          title: "名次",
          key: "showRank",
          width: 80,
          align: "left"
        },
        {
          title: "赛事",
          key: "eventsName",
          align: "left",
          render: (h, params) => {
            let self = this;
            let title = self.$config.userName(
              self.fieldObj.eventsName,
              self.fieldObj.eventsEnglishName
            );
            return h("span", title);
          }
        },
        {
          title: "选手名称",
          key: "userName",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h(
              "span",
              self.$config.userName(params.row.userName, params.row.englishName)
            );
          }
        },
        {
          title: "会员卡号",
          key: "memberNo",
          align: "left"
        },
        // {
        //   title: "国籍",
        //   key: "country",
        //   align: "left"
        // },
        {
          title: "第一轮",
          key: "roundFirst",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.roundFirst));
          }
        },
        {
          title: "第二轮",
          key: "roundSecond",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.roundSecond));
          }
        },
        {
          title: "第三轮",
          key: "roundThird",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.roundThird));
          }
        },
        {
          title: "第四轮",
          key: "roundFourth",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.roundFourth));
          }
        },
        {
          title: "杆数",
          key: "rodNumber",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.rodNumber));
          }
        },
        {
          title: "得分",
          key: "score",
          align: "left",
          render: (h, params) => {
            return h(
              "span",
              {
                style: {
                  color: "orange"
                }
              },
              params.row.score
            );
          }
        },
        {
          title: "阵容值",
          key: "kindTeam",
          align: "left",
          render: (h, params) => {
            let self = this;
            return h("span", self.$config.toStr(params.row.kindTeam));
          }
        }
      ],
      tableData: [],
      tabsList: [],
      tabsObj:  {
        '3': '男子业余',
        '4': '女子业余',
        '5': '青少年男子A组',
        '6': '青少年女子A组',
        '7': '青少年男子B组',
        '8': '青少年女子B组'
      }
    };
  },
  computed: {
    height: function() {
      return document.documentElement.clientHeight - 394;
    }
  },
  mounted() {
    let self = this;
    Promise.all([getDict({ code: "AG_OUT" }), getDict({ code: "AG_IN" })])
      .then(data => {
        self.AGOUTS = data[0];
        self.AGINS = data[1];
        this.getMatchById();
      })
      .catch(err => {
        this.getMatchById();
      });
  },
  methods: {
    getMatchById() {
      let self = this;
      api.getMatchById(self.fieldId).then(data => {
        self.fieldObj = data || {};
        self.fieldData = [self.fieldObj];
         self.stateFlag = data.scoreState !== "0";
        if (["1", "2"].indexOf(self.fieldObj.kindCode) >= 0) {
          self.fieldColumns = self.fieldColumns.filter(
            x => !["kindTeamAll", "kindTeamScore", "total"].includes(x.key)
          );
          self.tableColumns = self.tableColumns.filter(
            x => !["kindTeam"].includes(x.key)
          );
        }
        if (self.stateFlag) {
          self.fetchList();
        }
      });
    },
    // 获取数据
    fetchList() {
      let self = this;
      self.loading = true;
      api
        .queryList(self.page)
        .then(data => {
          self.tableData = data || [];
          self.tableData.forEach(x => {
            x.eventsName = self.fieldObj.eventsName;
          });
          if(["-1", "0"].indexOf(self.fieldObj.kindCode) >= 0) {
            self.tableData = _.groupBy(self.tableData, 'kindCode');
            self.tabsList = Object.keys(self.tableData)
            this.currentTab(self.tabsList[0])
          }
          self.loading = false;
        })
        .catch(error => {
          self.loading = false;
        });
    },
    downloadTemp() {
      let link = document.createElement('a');
      link.href = this.$config.fieldScoreExcelTempUrl;
      if(this.fieldObj.kindCode == '-1') {
        link.href = this.$config.fieldAmateurScoreExcelTempUrl;
      } else if(this.fieldObj.kindCode == '0') {
        link.href = this.$config.fieldTeenScoreExcelTempUrl;
      }
      link.download = '赛事成绩模版.xlsx';
      link.click();
    },
    currentTab(current) {
      let self = this;
      self.loading = true;
      let params = {
        fieldId: this.fieldId,
        kindCode: current
      }
      api.scoreKindTeam(params).then(data => {
        Object.assign(self.fieldData[0], {...data})
      })
      self.loading = false;
    },
    // 上传文件成功后发送请求解析
    getFieldData(fileUrl) {
      let self = this;
      let url = ''
      let params = {
        ftpFile: fileUrl,
        fieldId: self.fieldObj.fieldId,
        grandCode: self.fieldObj.gradeCode,
        kindCode: self.fieldObj.kindCode,
        qualifyingMatch: self.fieldObj.qualifyingMatch
      };
      let twoParams = {
        ftpFile: fileUrl,
        fieldId: self.fieldObj.fieldId,
      }
      if(["-1", "0"].indexOf(self.fieldObj.kindCode) >= 0) {
        url = '/fiedscore/importScore'
      } else if(["20"].indexOf(self.fieldObj.kindCode) >= 0) {
        url = '/fiedscore/importScoreExcell'
        params = twoParams
      } else {
        url = '/fiedscore/importExcell'
      }
      // let url = ["-1", "0"].indexOf(self.fieldObj.kindCode) >= 0? '/fiedscore/importScore' : '/fiedscore/importExcell'
      api.scoreUpload(params, url).then(data => {
        self.uploadData = data || [];
        let flag = false
        if(self.tableColumns.find(x=>x.key==='memberMarks')){
          self.tableColumns = self.tableColumns.filter(x=>x.key!='memberMarks')
        }
        // self.uploadData.filter(x => !(!x.memberMarks || x.memberMarks.includes('4'))).length==0 && (flag = true)
        self.uploadData.filter(x => {
          if((x.scoreList && x.scoreList[0].memberMarks && x.scoreList[0].memberMarks.includes('4'))) {flag = true}
          else if(!x.scoreList && x.memberMarks && x.memberMarks.includes('4')) {flag = true}
        })
        if(flag){
          self.stateFlag = true;
          self.isUpload = true;
          self.save(data);
        }else{
          self.stateFlag=null
          /**
           * 会员标识
           * 0 - 非会员
           * 1 - 会员号不正确
           * 2 - 国籍不正确
           * 3 - 姓名不正确
           * 4 - 正常
           */
          self.tableColumns.push({
            title: "错误原因",
            key: "memberMarks",
            align: "left",
            render: (h, params) => {
              let self = this;
              let arr = []
              const obj = {
                '0':'非会员',
                '1':'会员号不正确',
                '2':'国籍不正确',
                '3':'姓名不正确',
                '4':'正常',
                '5':'会员卡号重复'
              }
              params.row.memberMarks = params.row.memberMarks||[]
              let str = params.row.memberMarks.map(x=>obj[x]).join(",")
              return h("span",{
                style: {
                  color: "red"
                }
              }, str);
            }
          })
          self.uploadData.some(item => {
            if(item.scoreList) {
              let data = []
              self.uploadData.forEach(x => {
                data.push(...x.scoreList)

              })
             self.tableData = _.groupBy(data, 'kindCode');
            } else {
              self.tableData = [...self.uploadData]
            }
          })
          self.stateFlag=true;
          self.loading = false;
          this.$Message.error('上传文件错误，请重新上传文件');
        }
      });
    },
    // // 分页
    // changePage(pageNum) {
    //   this.page.pageNo = pageNum;
    //   this.fetchList();
    // },
    // 删除成绩
    del() {
      let self = this;
      api.scoreDel([self.fieldId]).then(flag => {
        self.isUpload = false;
        self.uploadData = [];
        // self.getMatchById();
      });
    },
    //保存
    save(params) {
      let self = this;
      let flag = params.some(item => item.scoreList)
      // 删除 原数据
      if(flag) {
        //  api
        // .scoreSave(params)
         api
        .scoreDel([self.fieldId])
        .then(data => {
          // 保存新上传数据
          return api.scoreSave(self.uploadData);
        })
        .then(data => {
          self.loading = true
          self.isUpload = false;
          self.getMatchById();
        })
        .catch(error => {
          self.uploadData = [];
          self.isUpload = false;
        });
      } else {
         api
        .scoreDel([self.fieldId])
        .then(data => {
          // 保存新上传数据
          return api.scoreAdd(self.uploadData);
        })
        .then(data => {
          // self.uploadData = [];
          let params = {
            fieldId: self.fieldId,
            roundStandard: self.uploadData[0].roundStandard,
            fieldCourt: self.uploadData[0].fieldCourt,
            kindTeamAll: self.uploadData[0].kindTeamAll,
            kindTeamScore: self.uploadData[0].kindTeamScore,
            total: self.uploadData[0].total
          };
          return api.scoreAddEndEdit(params);
        })
         .then(data => {
          self.loading = true
          self.isUpload = false;
          self.getMatchById();
        })
        .catch(error => {
          self.uploadData = [];
          self.isUpload = false;
        });
      }
    }
  }
};
</script>

<style scoped>
</style>
